package com.sniper.springmvc.jyzx;

import com.gentle.service.declare.Exception_Exception;
import com.gentle.service.declare.IDataService;
import com.sniper.springmvc.model.JyzxReceive;
import com.sniper.springmvc.mybatis.service.impl.JyzxReceiveService;
import com.sniper.springmvc.scheduler.JyzxImportWithScheduled;
import org.dom4j.DocumentException;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * 数据导入具体执行线程
 * <p>
 * Created by suzhen on 2017/4/12.
 */
public class JyzxImport implements Callable<JyzxImportBack> {

    private JyzxReceiveService jyzxReceiveService;
    private int start;
    private int pageSize;
    private CountDownLatch latch;

    private IDataService iDataService;

    public void setiDataService(IDataService iDataService) {
        this.iDataService = iDataService;
    }

    public JyzxImport(JyzxReceiveService jyzxReceiveService, int start, int pageSize, CountDownLatch latch) {
        this.jyzxReceiveService = jyzxReceiveService;
        this.start = start;
        this.pageSize = pageSize;
        this.latch = latch;
    }


    @Override
    public JyzxImportBack call() throws Exception {

        //读取一条数据。确定数据的总记录数
        String dataStr = null;

        try {
            dataStr = iDataService.getdata(JyzxImportWithScheduled.type, start, pageSize);
        } catch (Exception_Exception e) {
            e.printStackTrace();
        }
        JyzxData jyzxData = null;
        try {
            jyzxData = JyzxUtils.decodeStr(dataStr);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        assert jyzxData != null;
        List<JyzxReceive> lists = jyzxData.getModels();

        JyzxImportBack importBack = new JyzxImportBack();
        int saveCount = 0;
        int updateCount = 0;
        //读取处理数据
        for (JyzxReceive back : lists) {
            //检测数据是否存在
            if (back.getEntname() != null) {
                JyzxReceive receive = jyzxReceiveService.getReceive(back.getEntname(), "entname");
                //说明数据本地不存在
                if (receive == null) {
                    receive = new JyzxReceive();
                    BeanUtils.copyProperties(back, receive);
                    receive.setType(JyzxReceiveService.TYPE_RECEIVE);
                    jyzxReceiveService.insert(receive);
                    saveCount++;
                } else {
                    BeanUtils.copyProperties(back, receive);
                    receive.setType(JyzxReceiveService.TYPE_RECEIVE);
                    jyzxReceiveService.update(receive);
                    updateCount++;
                }
            }
        }
        //返回操作记录结果
        importBack.setSaveCount(saveCount);
        importBack.setUpdateCount(updateCount);
        latch.countDown();
        return importBack;
    }
}
